package com.ossean.projectmanager.projectsfilter;

import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;

import com.ossean.projectmanager.lasttabledao.OpenSourceProjectDao;
import com.ossean.projectmanager.lasttabledao.PointersDao;
import com.ossean.projectmanager.lasttabledao.RelativeMemoToOpenSourceProjectDao;
import com.ossean.projectmanager.model.OpenhubProject;
import com.ossean.projectmanager.model.GithubProject;
import com.ossean.projectmanager.model.OpenSourceProject;
import com.ossean.projectmanager.model.SourceForgeProject;
import com.ossean.projectmanager.parttabledao.PartProjectDao;

@Component("projectsFilter")
public class ProjectsFilter {
	@Resource
	private OpenSourceProjectDao lastProjectDao;

	@Resource
	private PartProjectDao partProjectDao;

	@Resource
	private RelativeMemoToOpenSourceProjectDao matchResultDao;

	Logger logger = Logger.getLogger(this.getClass());
	private final int batchsize = 5000;

	/**
	 * 对项目总表根据各个社区的特定字段做筛选
	 * 
	 * @throws InterruptedException
	 */
	public void filtratePrjs() {
		logger.info("Reading projects......");
		long startTime = System.currentTimeMillis();
		int startId = lastProjectDao.getMinId(0);
		while (true) {
			List<OpenSourceProject> prjsList = lastProjectDao
					.getBatchPrjs(startId,batchsize);
			if(prjsList.size()==0){
				logger.info((System.currentTimeMillis() - startTime)/1000);
				logger.info("Filter done......sleeping......");
				try {
					Thread.sleep(1000*60*15);// 筛选完成，休息15分钟
				} catch (InterruptedException e) {
					logger.error(e);
				}
				//startId = lastProjectDao.getMinId(0);
				//logger.info("restart Filter~");
			}
			else{
				logger.info("Filtering projects......");
				for (OpenSourceProject project : prjsList) {
					logger.info("project id： " + project.getId());
					String prjUrl = project.getUrl();
					String source = "";
					String url = "";
					if (prjUrl == null || "".equals(prjUrl)) {
						lastProjectDao.updateFiltratedPrj(project.getId(), 0);
						continue;
					}
					if (prjUrl.contains("|,|")) { // 即url中包含多个项目来源
						String firstUrl = StringUtils.splitByWholeSeparator(prjUrl,
								"|,|")[0];// 只对第一个，即去重时保留的最热的项目来源做筛选。
						source = StringUtils.splitByWholeSeparator(firstUrl, "|:|")[0]; // 从url字段中取得第一个来源社区。
						url = StringUtils.splitByWholeSeparator(firstUrl, "|:|")[1]; // 获得第一个url
					} else { // url只有一个项目来源
						source = StringUtils.splitByWholeSeparator(prjUrl, "|:|")[0];
						url = StringUtils.splitByWholeSeparator(prjUrl, "|:|")[1];
					}
					if (source != null && source.length() > 0) {
						source = source.toLowerCase();
					} else {
						continue;
					}
					if (source.equals("openhub")) {
						OpenhubProject openhubProject = partProjectDao
								.getOpenHubPrjByUrl(url); // 根据url从openhub的项目分表获得项目信息
						if (openhubProject != null
								&& openhubProject.getName() != null
								&& !"".equals(openhubProject.getName())
								&& openhubProject.getDescription() != null
								&& !"".equals(openhubProject.getDescription())
								&& openhubProject.getCode_repository() != null
								&& !openhubProject.getCode_repository().contains(
										"Add a code location")) { // openhub的筛选条件为name、description不为空，且该项目有版本库
								lastProjectDao.updateFiltratedPrj(project.getId(),
										1); // 筛选标识从0变为1，表示该项目经过筛选新增的
								matchResultDao.deleteMatchResult(
										getTargetTable(project.getId()),
										project.getId()); // 删除该项目的匹配结果，确保无之前的匹配结果
						} else {
							//lastProjectDao.deleteProject(project.getId());
							matchResultDao.deleteMatchResult(
									getTargetTable(project.getId()),
									project.getId()); // 删除该项目的匹配结果
						}
					} else if (source.equals("sourceforge")) {
						SourceForgeProject sourceforgeProject = partProjectDao
								.getSourceForgePrjByUrl(url); // 根据url从SourceForge的项目分表获得项目信息
						if (sourceforgeProject != null
								&& sourceforgeProject.getName() != null
								&& !"".equals(sourceforgeProject.getName())
								&& sourceforgeProject.getDescription() != null
								&& !"".equals(sourceforgeProject.getDescription())
								&& ((sourceforgeProject.getDownload_num() > 0) || (sourceforgeProject
										.getStars() > 0))) {
								lastProjectDao.updateFiltratedPrj(project.getId(),
										1); // 筛选标识从0变为1，表示该项目经过筛选新增的
								matchResultDao.deleteMatchResult(
										getTargetTable(project.getId()),
										project.getId()); // 删除该项目的匹配结果，确保无之前的匹配结果
						} else {
							//lastProjectDao.deleteProject(project.getId());
							matchResultDao.deleteMatchResult(
									getTargetTable(project.getId()),
									project.getId()); // 删除该项目的匹配结果
						}
					} else if (source.equals("oschina") || source.equals("apache")) {
						if (project.getFilration() == 0) {
							lastProjectDao.updateFiltratedPrj(project.getId(), 1); // 筛选标识从0变为1，表示该项目经过筛选新增的
							matchResultDao.deleteMatchResult(
									getTargetTable(project.getId()),
									project.getId()); // 删除该项目的匹配结果，确保无之前的匹配结果
						} 
					} else  
						if(source.equals("github")){
						GithubProject githubProject = partProjectDao
								.getGithubPrjByUrl(url); //根据URL从github分表中获取github
						//github项目的筛选规则是，forks>0,且名字不为空
						if(githubProject != null
						   && !"".equals(githubProject.getName())
						   &&githubProject.getName() != null
						   &&githubProject.getForks() > 0)
						{
							lastProjectDao.updateFiltratedPrj(project.getId(),1); // 筛选标识从0变为1，表示该项目经过筛选新增的
							matchResultDao.deleteMatchResult(
									getTargetTable(project.getId()),
									project.getId()); // 删除该项目的匹配结果，确保无之前的匹配结果
						}
						else
						{
							matchResultDao.deleteMatchResult(
									getTargetTable(project.getId()),
									project.getId()); // 删除该项目的匹配结果，确保无之前的匹配结果
						}
						
					}else
					{
						logger.info("Unknown source... source = " + source);
					}
				}
				startId = prjsList.get(prjsList.size()-1).getId()+1;
			}
			
			
		}
	}

	/**
	 * get the match result table's name
	 * 
	 * @param osp_id
	 * @return
	 */
	public static String getTargetTable(int ospId) {
		String targetTableName = "relative_memo_to_open_source_projects_70_lqk_test";
//		if (ospId >= 770000) {
//			targetTableName = "relative_memo_to_open_source_projects_70";
//		} else {
//			int a = 1 + ospId / 11000;
//			targetTableName = "relative_memo_to_open_source_projects_" + a;
//		}
		// if (osp_id < 500) {
		// targetTableName = "relative_memo_to_open_source_projects_1";
		// }
		// else if (osp_id >= 500 && osp_id < 1000) {
		// targetTableName = "relative_memo_to_open_source_projects_2";
		// }
		// else if (osp_id >= 1000 && osp_id < 1500) {
		// targetTableName = "relative_memo_to_open_source_projects_3";
		// }
		// else if (osp_id >= 1500 && osp_id < 2000) {
		// targetTableName = "relative_memo_to_open_source_projects_4";
		// }
		// else if (osp_id >= 2000 && osp_id < 3000) {
		// targetTableName = "relative_memo_to_open_source_projects_5";
		// }
		// else if (osp_id >= 3000 && osp_id < 5000) {
		// targetTableName = "relative_memo_to_open_source_projects_6";
		// }
		// else if (osp_id >= 5000 && osp_id < 7500) {
		// targetTableName = "relative_memo_to_open_source_projects_7";
		// }
		// else if (osp_id >= 7500 && osp_id < 10000) {
		// targetTableName = "relative_memo_to_open_source_projects_8";
		// }
		// else if (osp_id >= 10000 && osp_id < 310000) {
		// int a = 7 + osp_id/5000;
		// targetTableName = "relative_memo_to_open_source_projects_" + a;
		// }
		// else if (osp_id >= 310000) {
		// targetTableName = "relative_memo_to_open_source_projects_70";
		// }
		return targetTableName;
		// return "relative_memo_to_open_source_projects";
	}
}
